import React, {useRef, useState} from "react";
import ProForm, {
  FormInstance,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import {FooterToolbar} from '@ant-design/pro-layout';
import {Card, Form, Input, Spin} from 'antd';

import RegionCascader from '@/components/RegionCascader';
import FormAvatar from "@/components/FormAvatar";
import GridContainer from "@/components/GridContainer";
import {RuleObject, StoreValue} from "rc-field-form/lib/interface";
import {ProfileDTO, ProfileVO} from "@/types/common";

interface OrganizationFormProps{
  onFinish:(formData: ProfileDTO) => Promise<ProfileVO>;
  isModify?: boolean
}

const OrganizationForm: React.FC<OrganizationFormProps> = (props) => {

  const formRef = useRef<FormInstance>();

  const [loading,setLoading] = useState<boolean>(false);

  const checkPassword = (rule: RuleObject, value: StoreValue, callback: (error?: string) => void): Promise<void | any> | void => {
    const password = formRef.current?.getFieldValue(['adminUser','password']);
    return new Promise<void | any> ((resolve,reject) => {
      if (!value || value !== password) {
        reject('两次密码输入不一致');
      }else{
        resolve(value);
      }
    })
  };

  const checkAddress = (rule: RuleObject, value: StoreValue, callback: (error?: string) => void): Promise<void | any> | void => {
    return new Promise<void | any> ((resolve,reject) => {
      if (!value || value.length < 3) {
        reject('请选择注册地址');
      }else{
        resolve(value);
      }
    })
  };

  const onFinish=async (values:any) => {
    setLoading(true);
    const {organization}=values;
    organization.address={
      ...organization.address,
      provinceId:organization.region[0],
      cityId:organization.region[1],
      districtId:organization.region[2],
    }
    values.organization=organization;
    delete organization.region;
    return new Promise<boolean|void>((resolve, reject)=>{
      props.onFinish(values)
        .then((data)=>{
          setLoading(false);
          if(data){
            resolve();
            //跳转
          }else{
            reject();
          }
        });
    })
  }

  return (
      <GridContainer hasFooter={true}>
        <Spin spinning={loading}>
          <ProForm
            formRef={formRef}
            submitter={{
              render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
            }}
            onFinish={onFinish}
          >
            <Card title={'单位信息'} style={{marginBottom:24}}>
              <ProForm.Group>
                <Form.Item name={['organization','id']}>
                  <Input type={'hidden'} />
                </Form.Item>
                <ProFormText
                  width="md"
                  name={['organization','name']}
                  label="单位名称"
                  rules={[
                    {required:true,message:'请输入单位名称'}
                  ]}
                  placeholder="请输入单位名称"
                />
                <ProFormText
                  width="md"
                  name={['organization','unifiedSocialCreditCode']}
                  label="社会统一信用代码"
                  rules={[
                    {required:true,message:'请输入社会统一信用代码'}
                  ]}
                  placeholder="请输入社会统一信用代码"
                />
                <ProFormText
                  width="md"
                  name={['organization','legalRepresentative']}
                  label="法定代表人"
                  rules={[
                    {required:true,message:'请输入法定代表人'}
                  ]}
                  placeholder="请输入法定代表人"
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  width="md"
                  name={['organization','telephoneNumber']}
                  label="联系电话"
                  rules={[
                    {required:true,message:'请输入联系电话'}
                  ]}
                  placeholder="请输入联系电话"
                />
                <ProFormText
                  width="md"
                  name={['organization','email']}
                  label="邮箱"
                  rules={[
                    {type: 'email',required:true,message:'邮箱不是一个有效的email'}
                  ]}
                  placeholder="请输入邮箱"
                />
                <ProFormText
                  width="md"
                  name={['organization','officialWebsite']}
                  label="官网"
                  placeholder="请输入官网"
                />
              </ProForm.Group>
              <ProForm.Group align={'start'}>
                <Form.Item name={['organization','address','id']}>
                  <Input type={'hidden'} />
                </Form.Item>
                <Form.Item
                  className={'pro-field-md'}
                  name={['organization','region']}
                  label="注册地址"
                  required={true}
                  rules={[
                    { validator: checkAddress },
                  ]}
                >
                  <RegionCascader />
                </Form.Item>
                <ProFormTextArea
                  width="md"
                  label="详细地址"
                  name={['organization','address','detailAddress']}
                  rules={[
                    {required:true,message:'请输入详细地址'}
                  ]}
                  placeholder="请输入详细地址"
                />
                <ProFormTextArea
                  width="md"
                  label="简介"
                  name={['organization','briefIntroduction']}
                  placeholder="请输入简介"
                />
              </ProForm.Group>
              <ProForm.Group align={'start'}>
                <Form.Item name={['organization','logoId']} label="logo">
                  <FormAvatar />
                </Form.Item>
              </ProForm.Group>
            </Card>
            <Card title={'管理员信息'}>
              <ProForm.Group>
                <Form.Item name={['adminUser','id']}>
                  <Input type={'hidden'} />
                </Form.Item>
                <ProFormText
                  width="md"
                  name={['adminUser','name']}
                  label="姓名"
                  rules={[
                    {required:true,message:'请输入姓名'}
                  ]}
                  placeholder="请输入姓名"
                />
                <ProFormText
                  width="md"
                  name={['adminUser','email']}
                  label="邮箱"
                  rules={[
                    {type: 'email',required:true,message:'邮箱不是一个有效的email'}
                  ]}
                  placeholder="请输入邮箱"
                />
                <ProFormText
                  width="md"
                  name={['adminUser','mobile']}
                  label="手机"
                  rules={[
                    {required:true,message:'请输入手机'}
                  ]}
                  placeholder="请输入手机"
                />
              </ProForm.Group>
              {!props.isModify&&(
                <ProForm.Group>
                  <ProFormText
                    width="md"
                    name={['adminUser','username']}
                    label="用户名"
                    rules={[
                      {required:true,message:'请输入用户名'}
                    ]}
                    placeholder="请输入用户名"
                  />
                  <ProFormText.Password
                    width="md"
                    name={['adminUser','password']}
                    label="密码"
                    placeholder="请输入密码"
                    rules={[
                      {
                        required:true,
                        pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/,
                        message: '密码必须包含大小写字母、数字，长度为8-16位',
                      }
                    ]}
                  />
                  <ProFormText.Password
                    width="md"
                    name={['adminUser','confirmPassword']}
                    label="确认密码"
                    placeholder="请确认密码"
                    required={true}
                    rules={[
                      { validator: checkPassword },
                    ]}
                  />
                </ProForm.Group>
              )}
            </Card>
          </ProForm>
        </Spin>
      </GridContainer>
  );
};

export default OrganizationForm;
